import { toWxWeb, getWxPage, getQuery, getEnv } from "./util";

// 判断是否登录
function cbdIsLogin() {
  return new Promise((resolve, reject) => {
    try {
      bridge.userInfoPlugins.login().then(res => {
        const { isLogin } = res;
        if (isLogin == 1) return resolve(true);
        else return resolve(false);
      });
    } catch (e) {
      reject(e);
    }
  });
}

// 客户端登录
function cbdLogin() {
  return new Promise((resolve, reject) => {
    try {
      bridge.naviPlugins.requestLogin().then(res => {
        if (res.loginResult == 0) {
          resolve(true);
          return location.reload();
        } else {
          return resolve(false);
        }
      });
    } catch (e) {
      reject(e);
    }
  });
}

// cbd 内部拿 memberId
function cbdGetMemberId() {
  return new Promise((resolve, reject) => {
    try {
      bridge.userInfoPlugins.getSystemInfo().then(res => {
        const { memberId } = res.clientInfo;
        if (memberId) return resolve(memberId);
        else return resolve(false);
      });
    } catch (e) {
      reject(e);
    }
  });
}

// cbd 内部拿 clientInfo
function cbdGetClientInfo() {
  return new Promise((resolve, reject) => {
    try {
      bridge.userInfoPlugins.getSystemInfo().then(res => {
        const info = res.clientInfo;
        if (info) return resolve(info);
        else return resolve(false);
      });
    } catch (e) {
      reject(e);
    }
  });
}

// wx 拿手机号
function wxGetPhone() {
  return getQuery("mobileNo");
}

// wx 是否登录
function wxIsLogin() {
  return getQuery("isbind") == 1;
}

// 微信 app 是否登录
async function isLogin() {
  let env = await getEnv();
  if (env == "cbd") return await cbdIsLogin();
  else if (env == "mini") return wxIsLogin();

  return false;
}
// wx 登录
function wxLogin() {
  let bindBackUrl = location.href;
  toWxWeb(
    `/pages/common/mobileBind/mobileBind?refid=1686444655&pageindex=webview_redirect&redirect=${encodeURIComponent(
      bindBackUrl
    )}`
  );
}

// wx 拿sessionCode
function wxGetSessionCode() {
  return getQuery("sessionCode");
}

export {
  cbdGetMemberId,
  cbdLogin,
  cbdIsLogin,
  wxIsLogin,
  wxLogin,
  wxGetSessionCode,
  isLogin,
  wxGetPhone,
  cbdGetClientInfo
};
